#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->init();
    this->conn();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
    this->setWindowIcon(QIcon(":/images/favicon.ico"));
    this->setCentralWidget(ui->textEdit); //文本框填充整个工作区
    this->setWindowTitle("无标题 - 记事本");

    setting = new QSettings(QCoreApplication::applicationDirPath() + QString("/config.ini"), QSettings::IniFormat);
    //初始化默认值
    autoLine = false;                    //是否自动换行   否则不能使用转到
    statusBar = true;                    //是否显示状态栏
    ui->textEdit->setAcceptDrops(false); //设置文本输入框不接受鼠标放下
    this->setAcceptDrops(true);          //设置窗口接受鼠标放下

    setting->beginGroup("config"); //beginGroup与下面endGroup 相对应，“config”是标记
    //根据配置文件获取字体信息
    QString family = setting->value("family").toString();
    if (!family.isEmpty())
    { //设置了字体
        QFont font;
        font.setFamily(family);
        font.setPointSize(setting->value("point_size").toInt());
        font.setItalic(setting->value("italic").toBool());
        font.setBold(setting->value("bold").toBool());
        font.setOverline(setting->value("overline").toBool());
        font.setUnderline(setting->value("underline").toBool());
        ui->textEdit->setFont(font);
    }
    //获取存储的值
    statusBar = setting->value("status_bar").toInt() == 1 ? true : false;
    autoLine = setting->value("auto_go_line").toInt() == 1 ? true : false;
    setting->endGroup();

    ui->statusBar->setVisible(statusBar);                 //设置是否显示状态栏
    ui->actionStatusBar->setIconVisibleInMenu(statusBar); //是否显示状态栏勾中图标
    //设置状态栏
    ui->statusBar->setSizeGripEnabled(false); //设置是否显示右边的大小控制点

    //tips = new QLabel("  ", this);
    ranks = new QLabel(" 第 1 行，第 1 列      ", this);
    zoom = new QLabel(" 100% ", this);
    newline = new QLabel(" Windows(CRLF)   ", this);
    codeformat = new QLabel(" UTF-8         ", this);

    switch (autoLine)
    {
    case true:
        ui->actionAutoLine->setIconVisibleInMenu(true); //显示自动换行勾中图标
        ui->textEdit->setLineWrapMode(QTextEdit::WidgetWidth);
        ui->actionGoTO->setEnabled(false);
        break;
    case false:
        ui->actionAutoLine->setIconVisibleInMenu(false); //不显示自动换行勾中图标
        ui->textEdit->setLineWrapMode(QTextEdit::NoWrap);
        ui->actionGoTO->setEnabled(true);
        break;
    }
    //显示永久信息
    //ui->statusBar->addPermanentWidget(tips);
    ui->statusBar->addPermanentWidget(ranks);
    ui->statusBar->addPermanentWidget(zoom);
    ui->statusBar->addPermanentWidget(newline);
    ui->statusBar->addPermanentWidget(codeformat);

    //设置编辑菜单的不可用按钮
    ui->actionRevoke->setEnabled(false);
    ui->actionCut->setEnabled(false);
    ui->actionCopy->setEnabled(false);
    ui->actionDelete->setEnabled(false);
    ui->actionBing->setEnabled(false);
    ui->actionFind->setEnabled(false);
    ui->actionFindNext->setEnabled(false);
    ui->actionFindLast->setEnabled(false);
    ui->actionFindLast->setEnabled(false);
}

void MainWindow::conn()
{
    //文本框槽函数
    connect(this, &MainWindow::sendData, &goToDialog, &GoToDialog::receiveData);
    connect(ui->textEdit, &QTextEdit::textChanged, this, &MainWindow::textChangedSlot);
    connect(ui->textEdit, &QTextEdit::cursorPositionChanged, this, &MainWindow::cursorChangeSlot);
    connect(ui->textEdit, &QTextEdit::selectionChanged, this, &MainWindow::selectionChangedSlot);

    //文件菜单
    connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newFileSlot);
    connect(ui->actionNewWindow, &QAction::triggered, this, &MainWindow::newFileWindowSlot);
    connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::openFileSlot);
    connect(ui->actionSave, &QAction::triggered, this, &MainWindow::saveFileSlot);
    connect(ui->actionOtherSave, &QAction::triggered, this, &MainWindow::saveOtherFileSlot);
    connect(ui->actionPageSetting, &QAction::triggered, this, &MainWindow::PageSettingSlot);
    connect(ui->actionPrint, &QAction::triggered, this, &MainWindow::doPrintSlot);
    connect(ui->actionExit, &QAction::triggered, this, &MainWindow::exitAppSlot);

    //编辑菜单
    connect(ui->actionRevoke, &QAction::triggered, this, &MainWindow::undoSolt);
    connect(ui->actionCut, &QAction::triggered, this, &MainWindow::cutSolt);
    connect(ui->actionCopy, &QAction::triggered, this, &MainWindow::copySolt);
    connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::deleteSolt);
    connect(ui->actionBing, &QAction::triggered, this, &MainWindow::bingSolt);
    connect(ui->actionFind, &QAction::triggered, this, &MainWindow::findSlot);
    connect(&findDialog, &FindDialog::findtext, this, &MainWindow::FindTextSlot); //查找对话框槽函数
    connect(ui->actionFindNext, &QAction::triggered, this, &MainWindow::findNextSlot);
    connect(ui->actionFindLast, &QAction::triggered, this, &MainWindow::findLastSlot);
    connect(ui->actionReplace, &QAction::triggered, this, &MainWindow::replaceSlot);
    connect(&replaceDialog, &ReplaceDialog::findtext, this, &MainWindow::FindTextforReplaceSlot); //替换对话框槽函数→查找
    connect(&replaceDialog, &ReplaceDialog::replacetext, this, &MainWindow::ReplaceTextSlot);     //替换对话框槽函数→替换
    connect(ui->actionGoTO, &QAction::triggered, this, &MainWindow::goToSlot);
    connect(&goToDialog, &GoToDialog::goToLine, this, &MainWindow::goToLineSlot); //转到对话框槽函数
    connect(ui->actionSelectAll, &QAction::triggered, this, &MainWindow::selectAllSlot);
    connect(ui->actionTimeAndDate, &QAction::triggered, this, &MainWindow::timeAndDateSlot);

    //格式菜单
    connect(ui->actionAutoLine, &QAction::triggered, this, &MainWindow::autoLineSlot);
    connect(ui->actionFont, &QAction::triggered, this, &MainWindow::fontChooseSlot);

    //查看菜单
    connect(ui->actionZoomIn, &QAction::triggered, this, &MainWindow::ZoomInSlot);
    connect(ui->actionZoomOut, &QAction::triggered, this, &MainWindow::ZoomOutSlot);
    connect(ui->actionZoomDefault, &QAction::triggered, this, &MainWindow::ZoomDefaultSlot);
    connect(ui->actionStatusBar, &QAction::triggered, this, &MainWindow::statusBarSlot);

    //帮助菜单
    connect(ui->actionHelp, &QAction::triggered, this, &MainWindow::helpSlot);
    connect(ui->actionFeedback, &QAction::triggered, this, &MainWindow::FeedBackSlot);
    connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::aboutSlot);
}

//保存文本框文本到文件
void MainWindow::saveTextToFile()
{
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly))
    {
        QTextStream out(&file);
        out << ui->textEdit->document()->toPlainText();
        file.close();
        this->setWindowTitle(fileName.mid(fileName.lastIndexOf('/') + 1) + " - 记事本");
        fileContent = ui->textEdit->document()->toPlainText();
        ui->statusBar->showMessage("已保存", 3000);
    }
    else
    {
        QMessageBox box(QMessageBox::Question, "提示", "保存文件失败！", QMessageBox::Yes);
        box.setIcon(QMessageBox::Warning);
        box.button(QMessageBox::Yes)->setText("确定");
        box.exec();
    }
}
//读文件文本到文本框
void MainWindow::readFileToText()
{
    //得到路径不为空
    if (!fileName.isEmpty())
    {
        QFile *file = new QFile;
        file->setFileName(fileName);

        bool isOpen = file->open(QIODevice::ReadOnly);
        if (isOpen)
        {
            ui->textEdit->clear();
            QTextStream in(file);

            while (!in.atEnd())
            {
                ui->textEdit->append(in.readLine());
                //光标移动到开始位置
                ui->textEdit->moveCursor(QTextCursor::Start);
            }
            //已读完
            fileContent = ui->textEdit->document()->toPlainText();

            if (fileName.lastIndexOf("\\") != -1)
                this->setWindowTitle(fileName.mid(fileName.lastIndexOf('\\') + 1) + " - 记事本"); //设置标题
            else
                this->setWindowTitle(fileName.mid(fileName.lastIndexOf('/') + 1) + " - 记事本"); //设置标题

            file->close();
            ui->statusBar->showMessage("");
        }
        else
        {
            QMessageBox box(QMessageBox::Question, "提示", "打开文件失败！", QMessageBox::Yes);
            box.setIcon(QMessageBox::Warning);
            box.button(QMessageBox::Yes)->setText("确定");
            box.exec();
        }
    }
}

void MainWindow::ReplaceCharacter(QString value, bool isChecked)
{
    QTextCursor cursor = ui->textEdit->textCursor();

    cursor.insertText(value);                           //替换单个值
    ui->textEdit->moveCursor(cursor.PreviousCharacter); //光标移动到前一位

    if (!isChecked)                //不区分大小写
        ui->textEdit->find(value); //查找替换后的值高亮
    else                           //区分大小写
        ui->textEdit->find(value, QTextDocument::FindCaseSensitively);
}

void MainWindow::showMessage(QString value)
{
    QMessageBox box(QMessageBox::Warning, tr("记事本"), tr("找不到\"%1\" ").arg(value), QMessageBox::Ok);
    box.setIcon(QMessageBox::NoIcon);
    box.setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowStaysOnTopHint);
    box.exec();
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction(); //可以在这个窗口部件上拖放对象
}

void MainWindow::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if (!urls.isEmpty())
    {
        this->fileName = urls.last().toLocalFile();
        if (!this->fileName.isEmpty())
        {
            this->readFileToText(); //读文件
        }
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    //文档修改过 && 文本框不为空 && 读到的内容不是文本框的内容
    if (ui->textEdit->document()->isModified() && !ui->textEdit->document()->isEmpty() && fileContent != ui->textEdit->document()->toPlainText())
    {
        if (fileName.isEmpty())
            fileName = "无标题";
        QMessageBox box(QMessageBox::Question, tr("记事本"), tr("你想将更改保存到 %1 吗?").arg(fileName), QMessageBox::Save | QMessageBox::Ignore | QMessageBox::Cancel);
        box.setIcon(QMessageBox::NoIcon);
        box.button(QMessageBox::Save)->setText("保存");
        box.button(QMessageBox::Ignore)->setText("不保存");
        box.button(QMessageBox::Cancel)->setText("取消");
        int ret = box.exec();
        if (ret == QMessageBox::Save)
        {
            if (fileName == "无标题")
                fileName = "";
            saveFileSlot();
        }
        else if (ret == QMessageBox::Cancel)
        {
            if (fileName == "无标题")
                fileName = "";
            ui->statusBar->showMessage("");
            event->ignore();
            return;
        }
    }
    event->accept();
}

void MainWindow::wheelEvent(QWheelEvent *e)
{
    if (QApplication::keyboardModifiers() == Qt::ControlModifier) //ctrl键的判断
    {
        QPoint numDegrees = e->angleDelta();
        e->accept();
        if (!numDegrees.isNull() && (numDegrees.x() > 0 || numDegrees.y() > 0)) // 判断滚轮是否转动
        {
            ZoomInSlot();
        }
        else
        {
            ZoomOutSlot();
        }
    }
}

void MainWindow::textChangedSlot()
{
    ui->statusBar->showMessage("");
    if (ui->textEdit->document()->isEmpty())
    {
        if (fileName.isEmpty()) //没有保存到文件
            this->setWindowTitle("无标题 - 记事本");
        else //有文件
        {
            this->setWindowTitle("*" + fileName.mid(fileName.lastIndexOf('/') + 1) + " - 记事本");
            if (fileContent != ui->textEdit->document()->toPlainText())
                ui->statusBar->showMessage("未保存");
        }
    }
    else if (ui->textEdit->document()->isModified())
    {
        if (fileName.isEmpty())
        { //没有保存到文件
            this->setWindowTitle("*无标题 - 记事本");
            if (fileContent != ui->textEdit->document()->toPlainText())
                ui->statusBar->showMessage("未保存");
        }
        else
        { //有文件
            this->setWindowTitle("*" + fileName.mid(fileName.lastIndexOf('/') + 1) + " - 记事本");
            if (fileContent != ui->textEdit->document()->toPlainText())
                ui->statusBar->showMessage("未保存");
        }
        if (fileContent == ui->textEdit->document()->toPlainText())
        {
            this->setWindowTitle(fileName.mid(fileName.lastIndexOf('/') + 1) + " - 记事本");
        }
    }

    //撤销可用
    ui->actionRevoke->setEnabled(true);
    if (ui->textEdit->document()->isEmpty())
    {
        ui->actionFind->setEnabled(false);
        ui->actionFindNext->setEnabled(false);
        ui->actionFindLast->setEnabled(false);
    }
    else
    {
        ui->actionFind->setEnabled(true);
        ui->actionFindNext->setEnabled(true);
        ui->actionFindLast->setEnabled(true);
    }
}

void MainWindow::selectionChangedSlot()
{
    //如果编辑器中有选中区域，则打印选中区域
    QTextCursor cursor = ui->textEdit->textCursor(); //每次使用QTextCursor时，需要将现在QTextEdit的光标再传递给QTextCursor
    if (cursor.hasSelection())
    {
        ui->actionCut->setEnabled(true);
        ui->actionCopy->setEnabled(true);
        ui->actionDelete->setEnabled(true);
        ui->actionBing->setEnabled(true);
    }
    else
    {
        ui->actionCut->setEnabled(false);
        ui->actionCopy->setEnabled(false);
        ui->actionDelete->setEnabled(false);
        ui->actionBing->setEnabled(false);
    }
}

void MainWindow::cursorChangeSlot()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    int column = cursor.columnNumber() + 1;
    int block = cursor.blockNumber() + 1;
    ranks->setText("第 " + QString::number(block) + " 行，第 " + QString::number(column) + " 列      ");
}

void MainWindow::FindTextSlot(QString value, bool isChecked1, bool isChecked2, bool isUp)
{
    ui->statusBar->showMessage("");
    if (!isChecked1 && !isChecked2 && !isUp) //000 不区分大小写 不循环 向下找
    {
        if (!ui->textEdit->find(value))
            showMessage(value);
    }
    else if (!isChecked1 && !isChecked2 && isUp) //001 不区分大小写 不循环 向上找
    {
        if (!ui->textEdit->find(value, QTextDocument::FindBackward))
            showMessage(value);
    }
    else if (!isChecked1 && isChecked2 && !isUp) //010 不区分大小写 循环 向下找
    {
        //找不到则跳到顶部
        if (!ui->textEdit->find(value))
        {
            ui->statusBar->showMessage("从顶部开始查找下一项", 3000);
            ui->textEdit->moveCursor(QTextCursor::Start); //调整到顶部
            if (!ui->textEdit->find(value))
            {
                showMessage(value);
            }
        }
    }
    else if (!isChecked1 && isChecked2 && isUp) //011 不区分大小写 循环 向上找
    {
        //找不到则跳到底部
        if (!ui->textEdit->find(value, QTextDocument::FindBackward))
        {
            ui->statusBar->showMessage("从底部开始查找下一项", 3000);
            ui->textEdit->moveCursor(QTextCursor::End); //调整到底部
            if (!ui->textEdit->find(value, QTextDocument::FindBackward))
            {
                showMessage(value);
            }
        }
    }
    else if (isChecked1 && !isChecked2 && !isUp) //100 区分大小写 不循环 向下找
    {
        if (!ui->textEdit->find(value, QTextDocument::FindCaseSensitively))
            showMessage(value);
    }
    else if (isChecked1 && !isChecked2 && isUp) //101 区分大小写 不循环 向上找
    {
        if (!ui->textEdit->find(value, QTextDocument::FindBackward | QTextDocument::FindCaseSensitively))
            showMessage(value);
    }
    else if (isChecked1 && isChecked2 && !isUp) //110 区分大小写 循环 向下找
    {
        //找不到则跳到顶部
        if (!ui->textEdit->find(value, QTextDocument::FindCaseSensitively))
        {
            ui->statusBar->showMessage("从顶部开始查找下一项", 3000);
            ui->textEdit->moveCursor(QTextCursor::Start); //调整到顶部
            if (!ui->textEdit->find(value, QTextDocument::FindCaseSensitively))
            {
                showMessage(value);
            }
        }
    }
    else //区分大小写 循环 向上找
    {
        //找不到则跳到底部
        if (!ui->textEdit->find(value, QTextDocument::FindBackward | QTextDocument::FindCaseSensitively))
        {
            ui->statusBar->showMessage("从底部开始查找下一项", 3000);
            ui->textEdit->moveCursor(QTextCursor::End); //调整到底部
            if (!ui->textEdit->find(value, QTextDocument::FindBackward | QTextDocument::FindCaseSensitively))
            {
                showMessage(value);
            }
        }
    }

    QPalette palette = ui->textEdit->palette();
    palette.setColor(QPalette::Highlight, palette.color(QPalette::Active, QPalette::Highlight));
    ui->textEdit->setPalette(palette);
}

void MainWindow::FindTextforReplaceSlot(QString value, bool isChecked1, bool isChecked2)
{
    this->FindTextSlot(value, isChecked1, isChecked2, false);
}

void MainWindow::ReplaceTextSlot(QString target, QString value, bool isChecked1, bool isChecked2, bool isReplaceAll)
{
    ui->statusBar->showMessage("");
    if (!isChecked1) //不区分大小写
    {
        if (!isChecked2) //不循环
        {
            if (!ui->textEdit->find(target))
            {
                if (isReplaceAll)
                    return;
                showMessage(target);
                return;
            }
        }
        else //循环
        {
            if (!ui->textEdit->find(target))
            {
                ui->statusBar->showMessage("从顶部开始查找下一项", 3000);
                ui->textEdit->moveCursor(QTextCursor::Start); //调整到顶部
                if (!ui->textEdit->find(target))
                {
                    if (isReplaceAll)
                        return;
                    showMessage(target);
                    return;
                }
            }
        }
    }
    else //区分大小写
    {
        if (!isChecked2) //不循环
        {
            if (!ui->textEdit->find(target, QTextDocument::FindCaseSensitively))
            {
                showMessage(target);
                return;
            }
        }
        else //循环
        {
            if (!ui->textEdit->find(target, QTextDocument::FindCaseSensitively))
            {
                ui->statusBar->showMessage("从顶部开始查找下一项", 3000);
                ui->textEdit->moveCursor(QTextCursor::Start); //调整到顶部
                if (!ui->textEdit->find(target, QTextDocument::FindCaseSensitively))
                {
                    showMessage(target);
                    return;
                }
            }
        }
    }
    //选中高亮
    QPalette palette = ui->textEdit->palette();
    palette.setColor(QPalette::Highlight, palette.color(QPalette::Active, QPalette::Highlight));
    ui->textEdit->setPalette(palette);

    //替换
    if (isReplaceAll)
    {
        ReplaceCharacter(value, isChecked1);
        ReplaceTextSlot(target, value, isChecked1, isChecked2, isReplaceAll); //递归调用
    }
    else
    {
        ReplaceCharacter(value, isChecked1);
    }
}

void MainWindow::goToLineSlot(QString line)
{
    QTextCursor cursor = ui->textEdit->textCursor();
    if (line.toInt() > cursor.blockNumber() + 1)
    {
        QMessageBox box(QMessageBox::Question, "记事本 - 跳行", "行数超过了总行数", QMessageBox::Ok);
        box.setIcon(QMessageBox::NoIcon);
        box.button(QMessageBox::Ok)->setText("确定");
        box.setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowStaysOnTopHint);
        box.exec();
        return;
    }
    goToDialog.close();
    int position = ui->textEdit->document()->findBlockByLineNumber(line.toInt() - 1).position();
    cursor.setPosition(position, QTextCursor::MoveAnchor);
    ui->textEdit->setTextCursor(cursor);
}

void MainWindow::newFileSlot()
{
    //文档修改过 && 文本框不为空 && 读到的内容不是文本框的内容
    if (ui->textEdit->document()->isModified() && !ui->textEdit->document()->isEmpty() && fileContent != ui->textEdit->document()->toPlainText())
    {
        if (fileName.isEmpty())
            fileName = "无标题";
        QMessageBox box(QMessageBox::Question, tr("记事本"), tr("你想将更改保存到 %1 吗?").arg(fileName), QMessageBox::Save | QMessageBox::Ignore | QMessageBox::Cancel);
        box.setIcon(QMessageBox::NoIcon);
        box.button(QMessageBox::Save)->setText("保存");
        box.button(QMessageBox::Ignore)->setText("不保存");
        box.button(QMessageBox::Cancel)->setText("取消");
        int ret = box.exec();
        if (ret == QMessageBox::Save)
        {
            if (fileName == "无标题")
                fileName = "";
            saveFileSlot();
        }
        else if (ret == QMessageBox::Cancel)
        {
            if (fileName == "无标题")
                fileName = "";
            ui->statusBar->showMessage("");
            return;
        }
    }
    //不保存
    ui->textEdit->clear();
    setWindowTitle("无标题 - 记事本");
    //路径置空
    fileName = "";
}

void MainWindow::newFileWindowSlot()
{
    // 启动一个进程，然后使其和当前进程脱离关系
    QProcess::startDetached(QCoreApplication::applicationFilePath()); //指定App路径
}

void MainWindow::openFileSlot()
{
    //文档已经修改
    if (ui->textEdit->document()->isModified() && !ui->textEdit->document()->isEmpty() && fileContent != ui->textEdit->document()->toPlainText())
    {
        if (fileName.isEmpty())
            fileName = "无标题";
        QMessageBox box(QMessageBox::Question, tr("记事本"), tr("你想将更改保存到 %1 吗?").arg(fileName), QMessageBox::Save | QMessageBox::Ignore | QMessageBox::Cancel);
        box.setIcon(QMessageBox::NoIcon);
        box.button(QMessageBox::Save)->setText("保存");
        box.button(QMessageBox::Ignore)->setText("不保存");
        box.button(QMessageBox::Cancel)->setText("取消");
        int ret = box.exec();
        if (ret == QMessageBox::Save)
        {
            if (fileName == "无标题")
                fileName = "";
            saveFileSlot();
        }
        else if (ret == QMessageBox::Cancel)
        {
            if (fileName == "无标题")
                fileName = "";
            return;
        }
    }
    fileName = QFileDialog::getOpenFileName(this, tr("打开"), QDir::homePath(), tr("文本文件 (*.txt);;"));
    this->readFileToText();
}

void MainWindow::saveFileSlot()
{
    //判断是新建还是读取的文本
    if (fileName.isEmpty())
    { //新建
        //弹出保存文件对话框
        fileName = QFileDialog::getSaveFileName(this, tr("另存为"), QDir::homePath(), tr("文本文档(*.txt);;"));
        if (!fileName.isEmpty())
            this->saveTextToFile(); //读取的文本保存到文件
    }
    else
        this->saveTextToFile(); //读取的文本保存到文件
}

void MainWindow::saveOtherFileSlot()
{
    fileName = QFileDialog::getSaveFileName(this, tr("另存为"), QDir::homePath(), tr("文本文档(*.txt);;"));
    if (!fileName.isEmpty())
        this->saveTextToFile(); //读取的文本保存到文件
}

void MainWindow::PageSettingSlot()
{
    QPageSetupDialog p(&printer, this); // 创建页面设置对话框
    if (p.exec() == QDialog::Accepted)
        printer.setPageOrientation(QPageLayout::Landscape);
    else
        printer.setPageOrientation(QPageLayout::Portrait);
}

void MainWindow::doPrintSlot()
{
    QPrintDialog dlg(&printer, this); // 创建打印对话框
    //如果编辑器中有选中区域，则打印选中区域
    QTextCursor cursor = ui->textEdit->textCursor(); //每次使用QTextCursor时，需要将现在QTextEdit的光标再传递给QTextCursor
    if (cursor.hasSelection())
        dlg.setOptions(QAbstractPrintDialog::PrintSelection);
    // 如果在对话框中按下了打印按钮，则执行打印操作
    if (dlg.exec() == QDialog::Accepted)
        ui->textEdit->print(&printer);
}

void MainWindow::exitAppSlot()
{
    //文档已经修改
    if (ui->textEdit->document()->isModified() && !ui->textEdit->document()->isEmpty() && fileContent != ui->textEdit->document()->toPlainText())
    {
        if (fileName.isEmpty())
            fileName = "无标题";
        QMessageBox box(QMessageBox::Question, tr("记事本"), tr("你想将更改保存到 %1 吗?").arg(fileName), QMessageBox::Save | QMessageBox::Ignore | QMessageBox::Cancel);
        box.setIcon(QMessageBox::NoIcon);
        box.button(QMessageBox::Save)->setText("保存");
        box.button(QMessageBox::Ignore)->setText("不保存");
        box.button(QMessageBox::Cancel)->setText("取消");
        int ret = box.exec();
        if (ret == QMessageBox::Save)
        {
            if (fileName == "无标题")
                fileName = "";
            saveFileSlot();
        }
        else if (ret == QMessageBox::Cancel)
        {
            if (fileName == "无标题")
                fileName = "";
            return;
        }
    }
    this->close();
}

void MainWindow::undoSolt() { ui->textEdit->undo(); }
void MainWindow::cutSolt() { ui->textEdit->cut(); }
void MainWindow::copySolt() { ui->textEdit->copy(); }
void MainWindow::pasteSolt() { ui->textEdit->paste(); }
void MainWindow::deleteSolt()
{
    QTextCursor cursor = ui->textEdit->textCursor(); //每次使用QTextCursor时，需要将现在QTextEdit的光标再传递给QTextCursor
    if (cursor.hasSelection())
        cursor.deleteChar();
}

void MainWindow::bingSolt()
{
    QTextCursor cursor = ui->textEdit->textCursor(); //每次使用QTextCursor时，需要将现在QTextEdit的光标再传递给QTextCursor
    if (cursor.hasSelection())
    {
        QString URL = (tr("https://cn.bing.com/search?q=%1&form=NPCTXT").arg(cursor.selectedText())).toUtf8();
        QDesktopServices::openUrl(QUrl(URL));
    }
}

void MainWindow::findSlot() { findDialog.exec(); }

void MainWindow::findNextSlot()
{
    QTextCursor tc = ui->textEdit->textCursor();
    if (tc.selectedText().isEmpty())
        findDialog.exec();
    else
        FindTextSlot(tc.selectedText(), false, false, false);
}

void MainWindow::findLastSlot()
{
    QTextCursor tc = ui->textEdit->textCursor();
    if (tc.selectedText().isEmpty())
        findDialog.exec();
    else
        FindTextSlot(tc.selectedText(), false, false, true);
}

void MainWindow::replaceSlot() { replaceDialog.exec(); }
void MainWindow::goToSlot()
{
    emit sendData(ui->textEdit->textCursor().blockNumber() + 1);
    goToDialog.exec();
}

void MainWindow::selectAllSlot() { ui->textEdit->selectAll(); }

void MainWindow::timeAndDateSlot()
{
    QDateTime time = QDateTime::currentDateTime(); //获取系统现在的时间
    ui->textEdit->append(time.toString("hh:mm yyyy-MM-dd"));
}

void MainWindow::autoLineSlot()
{
    if (autoLine)
    {
        ui->textEdit->setLineWrapMode(QTextEdit::NoWrap);
        ui->actionGoTO->setEnabled(false);
        autoLine = false;
    }
    else
    {
        ui->textEdit->setLineWrapMode(QTextEdit::WidgetWidth);
        ui->actionGoTO->setEnabled(true);
        autoLine = true;
    }
    ui->actionAutoLine->setIconVisibleInMenu(autoLine);

    setting->beginGroup("config"); //beginGroup与下面endGroup 相对应，“config”是标记
    setting->setValue("auto_go_line", QVariant(autoLine ? "1" : "0"));
    setting->endGroup();
}

void MainWindow::fontChooseSlot()
{
    QFont textFont = ui->textEdit->font();
    bool ok;
    QFont font = QFontDialog::getFont(&ok, textFont, this, tr("字体选择"));
    if (ok)
    {
        ui->textEdit->setFont(font);
        setting->beginGroup("config"); //beginGroup与下面endGroup 相对应，“config”是标记
        setting->setValue("family", QVariant(font.family()));
        setting->setValue("point_size", QVariant(font.pointSize()));
        setting->setValue("italic", QVariant(font.italic() == true ? "1" : "0"));
        setting->setValue("bold", QVariant(font.bold() == true ? "1" : "0"));
        setting->setValue("overline", QVariant(font.overline() == true ? "1" : "0"));
        setting->setValue("underline", QVariant(font.underline() == true ? "1" : "0"));
        setting->endGroup();
    }
}

void MainWindow::ZoomInSlot()
{
    QString str = zoom->text().trimmed(); //去掉两边空格
    int pos = str.indexOf('%');
    int x = str.left(pos).toInt();
    if (x == 500)
    {
        zoom->setText(tr(" %1% ").arg(x));
        return;
    }
    else
    {
        ui->textEdit->zoomIn();
        x += 10;
        zoom->setText(tr(" %1% ").arg(x));
    }
}
void MainWindow::ZoomOutSlot()
{
    QString str = zoom->text().trimmed(); //去掉两边空格
    int pos = str.indexOf('%');
    int x = str.left(pos).toInt();
    if (x == 10)
    {
        zoom->setText(tr(" %1% ").arg(x));
        return;
    }
    else
    {
        ui->textEdit->zoomOut();
        x -= 10;
        zoom->setText(tr(" %1% ").arg(x));
    }
}

void MainWindow::ZoomDefaultSlot()
{
    setting->beginGroup("config"); //beginGroup与下面endGroup 相对应，“config”是标记
    //根据配置文件获取字体信息
    QString family = setting->value("family").toString();
    if (!family.isEmpty())
    { //设置了字体
        QFont font;
        font.setFamily(family);
        font.setPointSize(setting->value("point_size").toInt());
        ui->textEdit->setFont(font);
    }
    setting->endGroup();

    zoom->setText(tr(" 100% "));
}

void MainWindow::statusBarSlot()
{
    statusBar = !statusBar;
    ui->actionStatusBar->setIconVisibleInMenu(statusBar);
    ui->statusBar->setVisible(statusBar);

    setting->beginGroup("config"); //beginGroup与下面endGroup 相对应，“config”是标记
    setting->setValue("status_bar", QVariant(statusBar ? "1" : "0"));
    setting->endGroup();
}

void MainWindow::helpSlot()
{
    QString URL = tr("https://go.microsoft.com/fwlink/?LinkId=834783").toUtf8();
    QDesktopServices::openUrl(URL);
}

void MainWindow::FeedBackSlot()
{
    QString URL = tr("http://wpa.qq.com/msgrd?v=3&uin=1830412618&site=qq&menu=yes").toUtf8();
    QDesktopServices::openUrl(URL);
}

void MainWindow::aboutSlot()
{
    ABoutDialog aboutDialog;
    aboutDialog.exec();
}
